import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:meePet/utils/LogUtils.dart';
import 'package:visibility_detector/visibility_detector.dart';

abstract class BaseFragment extends StatefulWidget {}

abstract class BaseFragmentState<T extends BaseFragment> extends State<T>
    with WidgetsBindingObserver,AutomaticKeepAliveClientMixin {
  late String tag = "";
  final String _dTag = "BaseFragmentState_";

  //通过上下文获取page唯一标识
  String getClassName(BuildContext? _buildContext) {
    if (_buildContext == null) {
      return _dTag;
    }
    String className = _buildContext.toString();
    if (className == null) {
      return _dTag;
    }
    className = className.substring(0, className.indexOf("(")).toString();
    return className;
  }

  BaseFragment createFragment(BaseFragment fragment) {
    return fragment;
  }

  @override
  void initState() {
    super.initState();
    print("${tag}initState\n");
    tag = getClassName(context);
    onCreate();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    print("${tag}didChangeDependencies\n");
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    print("${tag}build\n");
    //return initView(context);
    return VisibilityDetector(
        key: Key(tag),
        onVisibilityChanged: _handleVisibilityChanged,
        child: initView(context));
  }

  void _handleVisibilityChanged(VisibilityInfo info) {
    if (info.visibleFraction > 0) {
      LogUtils.i("页面可见性visible");
      onResume();
    } else {
      LogUtils.i("页面可见性invisible");
      onPause();
    }
  }

  @override
  void didUpdateWidget(T oldWidget) {
    print("${tag}didUpdateWidget\n");
    super.didUpdateWidget(oldWidget);
  }

  @override
  void reassemble() {
    print("${tag}reassemble\n");
    super.reassemble();
  }

  @override
  void deactivate() {
    print("${tag}deactivate\n");
    super.deactivate();
  }

  @override
  void dispose() {
    print("${tag}dispose\n");
    WidgetsBinding.instance.removeObserver(this);
    onDestroy();
    super.dispose();
  }

  void onCreate() {
    print("${tag}onCreate\n");
  }

  void onResume() {
    print("${tag}onResume\n");
  }

  void onPause() {
    print("${tag}onPause\n");
  }

  void onDestroy() {
    print("${tag}onDestroy\n");
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        onResume();
        break;
      case AppLifecycleState.paused:
        onPause();
        break;
    }
  }

  ///主动关闭页面
  void finish() {
    dispose();
  }

  @override
  bool get wantKeepAlive => true;//默认保持状态，需要修改则重写该方法

  Widget initView(BuildContext context);
}
